package com.adcc.swingui.factory;

import java.awt.Container;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JPopupMenu;

import org.apache.log4j.Logger;

import com.adcc.swingui.base.DefaultMenuBar;
import com.adcc.swingui.bean.MenuRightBean;
import com.adcc.swingui.conf.MenuRightBarConf;

public class MenuRightFactory {
	private static Logger logger = Logger.getLogger(MenuRightFactory.class);
	private static Map<String, JPopupMenu> map = new HashMap<String, JPopupMenu>();

	public static void create(String[] name, Container container) {
		for (int i = 0; i < name.length; i++) {
			if (map.containsKey(name[i])) {
				logger.warn("右键菜单对象已经存在" + name[i]);
			}
			MenuRightBean bean = MenuRightBarConf.getMenuRightConf().get(
					name[i]);
			JPopupMenu popupMenu = null;
			if (bean != null) {
				try {
					Class c = Class.forName(bean.getClassUrl());
					Constructor con = c
							.getConstructor(new Class[] { Container.class });
					DefaultMenuBar o = (DefaultMenuBar) con
							.newInstance(container);
					popupMenu = (JPopupMenu) o.buildButton(name[i]);
				} catch (Exception e) {
					logger.error("右键菜单创建失败" + bean.getClassUrl()
							+ e.getMessage());
				}
			} else {
				logger.error("右键菜单对象配置不存在" + name[i]);
			}
			// 菜单缓存到内存
			map.put(name[i], popupMenu);
		}
	}

	public static JPopupMenu createSingle(Container container, String path,
			List<String> privilege) {
		JPopupMenu popupMenu = null;
		List<MenuRightBean> list = MenuRightBarConf.getMenuRight(path,
				privilege);
		if (list != null && list.size() > 0) {
			MenuRightBean bean = list.get(list.size() - 1);
			try {
				Class c = Class.forName(bean.getClassUrl());
				Constructor con = c
						.getConstructor(new Class[] { Container.class });
				DefaultMenuBar o = (DefaultMenuBar) con.newInstance(container);
				popupMenu = (JPopupMenu) o.buildButton(bean.getName());
			} catch (Exception e) {
				logger.error("右键菜单创建失败" + bean.getClassUrl() + e.getMessage());
			}
		} else {
			logger.error("右键菜单对象配置不存在");
		}
		return popupMenu;
	}
}
